import { Request, Response } from 'express';
import Student, { IStudent } from '../models/student.model';

/**
 * 学生信息控制器
 */
export class StudentController {
  
  /**
   * 创建学生信息
   * POST /api/students
   */
  static async createStudent(req: Request, res: Response) {
    try {
      const { studentNo, name, className, grade, email, phone, gender } = req.body;

      // 检查学号是否已存在
      const existingStudent = await Student.findOne({ studentNo });
      if (existingStudent) {
        return res.status(409).json({
          success: false,
          message: '学号已存在',
          code: 409
        });
      }

      // 创建新学生
      const student = new Student({
        studentNo,
        name,
        className,
        grade,
        email,
        phone,
        gender
      });

      await student.save();

      res.status(201).json({
        success: true,
        data: student,
        message: '学生信息创建成功',
        code: 201
      });
    } catch (error: any) {
      console.error('创建学生信息失败:', error);
      res.status(400).json({
        success: false,
        message: error.message || '创建学生信息失败',
        code: 400
      });
    }
  }

  /**
   * 获取学生列表（支持分页、筛选）
   * GET /api/students?page=1&limit=10&className=一班&minGrade=60&maxGrade=100&keyword=张三
   */
  static async getStudents(req: Request, res: Response) {
    try {
      const {
        page = 1,
        limit = 10,
        className,
        minGrade,
        maxGrade,
        keyword,
        sortBy = 'createdAt',
        order = 'desc'
      } = req.query;

      // 构建查询条件
      const query: any = { isActive: true };

      // 班级筛选
      if (className) {
        query.className = className;
      }

      // 成绩范围筛选
      if (minGrade || maxGrade) {
        query.grade = {};
        if (minGrade) query.grade.$gte = Number(minGrade);
        if (maxGrade) query.grade.$lte = Number(maxGrade);
      }

      // 关键词搜索（姓名或学号）
      if (keyword) {
        query.$or = [
          { name: { $regex: keyword, $options: 'i' } },
          { studentNo: { $regex: keyword, $options: 'i' } }
        ];
      }

      // 分页参数
      const pageNum = Math.max(1, Number(page));
      const limitNum = Math.min(100, Math.max(1, Number(limit)));
      const skip = (pageNum - 1) * limitNum;

      // 排序
      const sortOptions: any = {};
      sortOptions[sortBy as string] = order === 'asc' ? 1 : -1;

      // 执行查询
      const [students, total] = await Promise.all([
        Student.find(query)
          .sort(sortOptions)
          .skip(skip)
          .limit(limitNum)
          .lean(),
        Student.countDocuments(query)
      ]);

      res.json({
        success: true,
        data: {
          students,
          pagination: {
            page: pageNum,
            limit: limitNum,
            total,
            pages: Math.ceil(total / limitNum)
          }
        },
        message: '获取学生列表成功',
        code: 200
      });
    } catch (error: any) {
      console.error('获取学生列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取学生列表失败',
        code: 500
      });
    }
  }

  /**
   * 获取单个学生详情
   * GET /api/students/:id
   */
  static async getStudentById(req: Request, res: Response) {
    try {
      const { id } = req.params;

      const student = await Student.findById(id);
      if (!student) {
        return res.status(404).json({
          success: false,
          message: '学生不存在',
          code: 404
        });
      }

      res.json({
        success: true,
        data: student,
        message: '获取学生详情成功',
        code: 200
      });
    } catch (error: any) {
      console.error('获取学生详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取学生详情失败',
        code: 500
      });
    }
  }

  /**
   * 更新学生信息
   * PUT /api/students/:id
   */
  static async updateStudent(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const updateData = req.body;

      // 不允许修改学号
      delete updateData.studentNo;
      delete updateData.createdAt;

      // 如果修改学号，需要检查是否冲突
      if (updateData.studentNo) {
        const existing = await Student.findOne({
          studentNo: updateData.studentNo,
          _id: { $ne: id }
        });
        if (existing) {
          return res.status(409).json({
            success: false,
            message: '学号已被其他学生使用',
            code: 409
          });
        }
      }

      const student = await Student.findByIdAndUpdate(
        id,
        { $set: updateData },
        { new: true, runValidators: true }
      );

      if (!student) {
        return res.status(404).json({
          success: false,
          message: '学生不存在',
          code: 404
        });
      }

      res.json({
        success: true,
        data: student,
        message: '学生信息更新成功',
        code: 200
      });
    } catch (error: any) {
      console.error('更新学生信息失败:', error);
      res.status(400).json({
        success: false,
        message: error.message || '更新学生信息失败',
        code: 400
      });
    }
  }

  /**
   * 删除学生信息（软删除）
   * DELETE /api/students/:id
   */
  static async deleteStudent(req: Request, res: Response) {
    try {
      const { id } = req.params;

      // 软删除：标记为非活跃
      const student = await Student.findByIdAndUpdate(
        id,
        { isActive: false },
        { new: true }
      );

      if (!student) {
        return res.status(404).json({
          success: false,
          message: '学生不存在',
          code: 404
        });
      }

      res.json({
        success: true,
        data: null,
        message: '学生信息删除成功',
        code: 200
      });
    } catch (error: any) {
      console.error('删除学生信息失败:', error);
      res.status(500).json({
        success: false,
        message: '删除学生信息失败',
        code: 500
      });
    }
  }

  /**
   * 获取成绩统计分析
   * GET /api/students/analysis/statistics?className=一班
   */
  static async getStatistics(req: Request, res: Response) {
    try {
      const { className } = req.query;

      // 基础统计
      const matchStage: any = { isActive: true };
      if (className) {
        matchStage.className = className;
      }

      const [stats, distribution] = await Promise.all([
        Student.aggregate([
          { $match: matchStage },
          {
            $group: {
              _id: null,
              totalStudents: { $sum: 1 },
              avgGrade: { $avg: '$grade' },
              maxGrade: { $max: '$grade' },
              minGrade: { $min: '$grade' }
            }
          }
        ]),
        Student.aggregate([
          { $match: matchStage },
          {
            $bucket: {
              groupBy: '$grade',
              boundaries: [0, 60, 80, 90, 101],
              default: 'other',
              output: {
                count: { $sum: 1 },
                percentage: { $sum: 1 }
              }
            }
          }
        ])
      ]);

      // 计算百分比
      const total = stats[0]?.totalStudents || 0;
      const distributionData = {
        excellent: { count: 0, percentage: 0 },  // 90-100
        good: { count: 0, percentage: 0 },       // 80-89
        pass: { count: 0, percentage: 0 },       // 60-79
        fail: { count: 0, percentage: 0 }        // 0-59
      };

      distribution.forEach((item: any) => {
        const count = item.count;
        const percentage = total > 0 ? ((count / total) * 100).toFixed(2) : 0;
        
        if (item._id === 90) {
          distributionData.excellent = { count, percentage: Number(percentage) };
        } else if (item._id === 80) {
          distributionData.good = { count, percentage: Number(percentage) };
        } else if (item._id === 60) {
          distributionData.pass = { count, percentage: Number(percentage) };
        } else if (item._id === 0) {
          distributionData.fail = { count, percentage: Number(percentage) };
        }
      });

      res.json({
        success: true,
        data: {
          basic: stats[0] || {
            totalStudents: 0,
            avgGrade: 0,
            maxGrade: 0,
            minGrade: 0
          },
          distribution: distributionData,
          className: className || '全部班级'
        },
        message: '获取统计数据成功',
        code: 200
      });
    } catch (error: any) {
      console.error('获取统计数据失败:', error);
      res.status(500).json({
        success: false,
        message: '获取统计数据失败',
        code: 500
      });
    }
  }

  /**
   * AI生成学习建议报告
   * POST /api/students/analysis/ai-report
   */
  static async generateAIReport(req: Request, res: Response) {
    try {
      const { studentId, className } = req.body;

      let reportData: any = {};

      // 如果指定学生ID，生成个人报告
      if (studentId) {
        const student = await Student.findById(studentId);
        if (!student) {
          return res.status(404).json({
            success: false,
            message: '学生不存在',
            code: 404
          });
        }

        // AI生成个人学习建议
        const personalAdvice = StudentController.generatePersonalAdvice(student);
        reportData = {
          type: 'personal',
          student: {
            name: student.name,
            studentNo: student.studentNo,
            className: student.className,
            grade: student.grade,
            gradeLevel: student.getGradeLevel()
          },
          analysis: personalAdvice
        };
      } 
      // 否则生成班级报告
      else if (className) {
        const classStats: any = await (Student as any).getClassAverage(className);
        if (!classStats) {
          return res.status(404).json({
            success: false,
            message: '班级不存在或无学生数据',
            code: 404
          });
        }

        // AI生成班级分析建议
        const classAdvice = StudentController.generateClassAdvice(classStats);
        reportData = {
          type: 'class',
          className,
          statistics: classStats,
          analysis: classAdvice
        };
      } else {
        return res.status(400).json({
          success: false,
          message: '请提供studentId或className参数',
          code: 400
        });
      }

      res.json({
        success: true,
        data: reportData,
        message: 'AI分析报告生成成功',
        code: 200
      });
    } catch (error: any) {
      console.error('生成AI报告失败:', error);
      res.status(500).json({
        success: false,
        message: '生成AI报告失败',
        code: 500
      });
    }
  }

  /**
   * AI辅助：生成个人学习建议
   */
  private static generatePersonalAdvice(student: IStudent): any {
    const grade = student.grade;
    let suggestions: string[] = [];
    let strengths: string[] = [];
    let improvements: string[] = [];

    if (grade >= 90) {
      strengths.push('成绩优秀，掌握了课程核心知识点');
      strengths.push('学习能力强，具备良好的学习习惯');
      suggestions.push('建议参加学科竞赛，进一步提升专业能力');
      suggestions.push('可以尝试深入学习相关领域的进阶知识');
      suggestions.push('考虑担任学习小组组长，帮助其他同学');
    } else if (grade >= 80) {
      strengths.push('成绩良好，基础知识掌握扎实');
      improvements.push('部分知识点理解不够深入');
      suggestions.push('建议加强薄弱环节的针对性练习');
      suggestions.push('多参与课堂讨论，提升思维活跃度');
      suggestions.push('向优秀同学请教学习方法');
    } else if (grade >= 60) {
      improvements.push('基础知识掌握不够牢固');
      improvements.push('学习方法需要改进');
      suggestions.push('建议制定详细的学习计划，每天坚持复习');
      suggestions.push('及时向老师请教不懂的问题');
      suggestions.push('参加课外辅导，巩固基础知识');
      suggestions.push('增加练习题量，提升解题能力');
    } else {
      improvements.push('基础知识薄弱，需要重点补习');
      improvements.push('学习态度需要调整');
      suggestions.push('建议从基础知识开始系统复习');
      suggestions.push('每天安排固定时间学习，养成良好习惯');
      suggestions.push('寻求老师和家长的帮助，制定提升计划');
      suggestions.push('不要灰心，相信通过努力一定能进步');
    }

    return {
      gradeLevel: student.getGradeLevel(),
      score: grade,
      strengths,
      improvements,
      suggestions,
      motivationalQuote: StudentController.getMotivationalQuote(grade)
    };
  }

  /**
   * AI辅助：生成班级分析建议
   */
  private static generateClassAdvice(classStats: any): any {
    const avgGrade = classStats.avgGrade;
    let overallAssessment: string;
    let suggestions: string[] = [];

    if (avgGrade >= 85) {
      overallAssessment = '班级整体成绩优秀，学习氛围浓厚';
      suggestions.push('继续保持良好的学习风气');
      suggestions.push('鼓励学生参加学科竞赛和课外拓展');
      suggestions.push('优秀学生可以建立学习帮扶小组');
    } else if (avgGrade >= 75) {
      overallAssessment = '班级整体成绩良好，仍有提升空间';
      suggestions.push('加强对中等成绩学生的关注和辅导');
      suggestions.push('组织学习经验分享会');
      suggestions.push('针对薄弱知识点进行专项训练');
    } else if (avgGrade >= 60) {
      overallAssessment = '班级整体成绩及格，需要重点提升';
      suggestions.push('分析学生成绩分化原因，因材施教');
      suggestions.push('增加课后辅导时间');
      suggestions.push('加强与家长的沟通，形成家校合力');
    } else {
      overallAssessment = '班级整体成绩需要紧急改善';
      suggestions.push('全面分析教学方法和学生学习状况');
      suggestions.push('制定详细的成绩提升方案');
      suggestions.push('增加个别辅导，关注每位学生进步');
    }

    return {
      overallAssessment,
      averageScore: avgGrade.toFixed(2),
      highestScore: classStats.maxGrade,
      lowestScore: classStats.minGrade,
      totalStudents: classStats.totalStudents,
      suggestions
    };
  }

  /**
   * 获取激励名言
   */
  private static getMotivationalQuote(grade: number): string {
    const quotes = {
      excellent: [
        '天才是1%的灵感加99%的汗水。——爱迪生',
        '成功源于勤奋，学习在于坚持。',
        '你的优秀不是偶然，继续保持！'
      ],
      good: [
        '再努力一点，你会更优秀！',
        '成功就在不远处，坚持就是胜利。',
        '相信自己，你可以做得更好！'
      ],
      pass: [
        '每一次努力都是进步的阶梯。',
        '不积跬步无以至千里，坚持学习！',
        '只要不放弃，就一定能成功！'
      ],
      fail: [
        '失败是成功之母，不要气馁！',
        '今天的努力，是明天的希望。',
        '相信自己，你一定可以进步！'
      ]
    };

    let category: keyof typeof quotes = 'fail';
    if (grade >= 90) category = 'excellent';
    else if (grade >= 80) category = 'good';
    else if (grade >= 60) category = 'pass';

    const quoteList = quotes[category];
    return quoteList[Math.floor(Math.random() * quoteList.length)];
  }

  /**
   * 批量导入学生信息
   * POST /api/students/batch
   */
  static async batchCreateStudents(req: Request, res: Response) {
    try {
      const { students } = req.body;

      if (!Array.isArray(students) || students.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请提供有效的学生数据数组',
          code: 400
        });
      }

      // 检查学号重复
      const studentNos = students.map(s => s.studentNo);
      const duplicates = await Student.find({ studentNo: { $in: studentNos } });
      
      if (duplicates.length > 0) {
        return res.status(409).json({
          success: false,
          message: `以下学号已存在: ${duplicates.map(d => d.studentNo).join(', ')}`,
          code: 409
        });
      }

      // 批量插入
      const result = await Student.insertMany(students, { ordered: false });

      res.status(201).json({
        success: true,
        data: {
          inserted: result.length,
          students: result
        },
        message: `成功导入${result.length}条学生信息`,
        code: 201
      });
    } catch (error: any) {
      console.error('批量导入失败:', error);
      res.status(400).json({
        success: false,
        message: error.message || '批量导入失败',
        code: 400
      });
    }
  }
}
